import os
import subprocess
import uuid

from Logs.log_handle import get_log

# 获取日志对象
log = get_log(os.path.basename(__file__))


def generate_script_file(code: str) -> str:
    """
    在临时目录中生成一个 Python 脚本文件，并返回文件路径。
    """
    root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    dir_path = os.path.join(root_path, "automatic_scripting", "run_scripting")
    os.makedirs(dir_path, exist_ok=True)
    filename = f"{uuid.uuid4().hex}.py"
    file_path = os.path.join(dir_path, filename)
    with open(file_path, "w", encoding="utf-8") as f:
        f.write("# -*- coding: utf-8 -*-\n")
        f.write(code)
    return file_path


def cleanup_file(path: str):
    """
    删除临时脚本文件。
    """
    try:
        os.remove(path)
    except Exception as e:
        log.error(f"删除临时脚本失败: {e}")


def stream_process(file_path: str):
    """
    使用 subprocess 执行脚本，并逐行 yield stdout/stderr。
    """
    proc = subprocess.Popen(
        ["python", file_path],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        bufsize=1,
        encoding="utf-8"
    )
    # 输出流
    for line in proc.stdout or []:
        yield f"data: {line.rstrip()}\n\n"
    for line in proc.stderr or []:
        yield f"data: ERROR: {line.rstrip()}\n\n"
    proc.wait()
    yield f"data: PROCESS_EXIT_CODE: {proc.returncode}\n\n"
